<?php

namespace App\Http\Middleware;

use App\Services\PermissionService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

/**
 * 权限中间件
 * 检查用户是否有访问当前路由的权限
 */
class PermissionMiddleware
{
    public function __construct(
        private PermissionService $permissionService
    ) {}

    /**
     * 处理传入请求
     */
    public function handle(Request $request, Closure $next, string $permission = null)
    {
        // 获取当前用户
        $user = Auth::user();

        if (!$user) {
            Log::warning('Permission middleware: 未认证用户尝试访问', [
                'uri' => $request->getUri(),
                'method' => $request->getMethod(),
                'ip' => $request->getClientIp(),
            ]);

            return response()->json([
                'success' => false,
                'message' => '未授权访问，请先登录'
            ], 401);
        }

        // 检查路由权限
        $method = $request->getMethod();
        $uri = $request->getPathInfo();

        if (!$this->permissionService->canAccessRoute($user, $method, $uri)) {
            Log::warning('Permission middleware: 用户权限不足', [
                'user_id' => $user->id,
                'username' => $user->username,
                'uri' => $uri,
                'method' => $method,
                'ip' => $request->getClientIp(),
            ]);

            return response()->json([
                'success' => false,
                'message' => '权限不足，访问被拒绝'
            ], 403);
        }

        // 如果指定了具体权限，额外检查
        if ($permission && !$this->permissionService->hasPermission($user, $permission)) {
            Log::warning('Permission middleware: 用户缺少指定权限', [
                'user_id' => $user->id,
                'username' => $user->username,
                'permission' => $permission,
                'uri' => $uri,
                'method' => $method,
            ]);

            return response()->json([
                'success' => false,
                'message' => '权限不足，缺少必要的权限：' . $permission
            ], 403);
        }

        return $next($request);
    }
}
